import qs from 'qs'
import { Message } from 'element-ui'
//import Token from '@/services/token'
import router from '@/router'
import store from '@/store'

const CONTENT_TYPE_FORM = 'application/x-www-form-urlencoded; charset=UTF-8'
const CONTENT_TYPE_JSON = 'application/json; charset=UTF-8'
const HOST = process.env.NODE_ENV === 'beta' ? Config.BETAHOST : ''

// 设置拦截器，记录请求，在路由跳转时取消上个路由的请求
axios.interceptors.request.use(
  config => {
    config.cancelToken = new axios.CancelToken(function(cancel) {
      store.commit('PUSH_TOKEN', { cancelToken: cancel })
    })
    config.timeout = 30000 // 超时时间
    return config
  },
  err => {
    return Promise.reject(err)
  }
)
function makeUrl(path, query) {
  query = query || {}
  if (path[0] !== '/') {
    path = `/${path}`
  }
  //为请求生成随机参数，防止浏览器缓存请求结果
  query.r = Math.random()
    .toString()
    .replace(/^0\./, '')
  return `${HOST}${path}?${qs.stringify(query, { arrayFormat: 'repeat' })}`
}

async function handleError(e, rej, noTip = false) {
  Loading.hide()
  if (!e.response) {
    rej(e)
    return
  }
  if (e.response.status === 401) {
    // token 过期
    Message.closeAll()
    Tip.warn('用户未认证！正在跳转至登录页面...')
    await Utils.sleep(500)
    if (process.env.NODE_ENV === 'beta') {
      window.location.href =
        'http://192.168.11.214/v2-static/management-platform/#/login'
    } else if (process.env.NODE_ENV === 'production') {
      window.location.href =
        'https://cloud.veryxiang.com/v2-static/management-platform/#/login'
    }
  } else if (e.response.status === 403) {
    router.replace({
      name: 'AccessDeny'
    })
  } else {
    if (!noTip) {
      Tip.error(e.response.data.message)
    }
  }
  rej(e)
}

export default {
  get(path, data, options = {}) {
    let p = new Promise(async function(resolve, reject) {
      try {
        let resp = await axios.get(makeUrl(path, data), {
          headers: {
            //'x-ca-stage': process.env.VUE_APP_STAGE,
            Authorization: `Bearer ${TokenService.get()}`
          }
        })
        resolve(resp.data)
      } catch (e) {
        handleError(e, reject, options.noTip)
      }
    })
    return p
  },

  post(path, data, options = {}) {
    let p = new Promise(async function(resolve, reject) {
      try {
        let resp = await axios.post(makeUrl(path, null), data, {
          headers: {
            'content-type': options.form
              ? CONTENT_TYPE_FORM
              : CONTENT_TYPE_JSON,
            //'x-ca-stage': process.env.VUE_APP_STAGE,
            Authorization: `Bearer ${TokenService.get()}`
          }
        })
        resolve(resp.data)
      } catch (e) {
        handleError(e, reject, options.noTip)
      }
    })
    return p
  },

  put(path, data, options = {}) {
    let p = new Promise(async function(resolve, reject) {
      try {
        let resp = await axios.put(makeUrl(path, null), data, {
          headers: {
            'content-type': options.form
              ? CONTENT_TYPE_FORM
              : CONTENT_TYPE_JSON,
            //'x-ca-stage': process.env.VUE_APP_STAGE,
            Authorization: `Bearer ${TokenService.get()}`
          }
        })
        resolve(resp.data)
      } catch (e) {
        handleError(e, reject, options.noTip)
      }
    })
    return p
  },

  delete(path, data, options = {}) {
    let p = new Promise(async function(resolve, reject) {
      try {
        let resp = await axios.delete(makeUrl(path, data), {
          headers: {
            //'x-ca-stage': process.env.VUE_APP_STAGE,
            Authorization: `Bearer ${TokenService.get()}`
          },
          data: options.data || null
        })
        resolve(resp.data)
      } catch (e) {
        handleError(e, reject, options.noTip)
      }
    })
    return p
  }
}
